package cate.game.play.part;

import cate.game.play.fighter.HallowFighter;
import cate.game.play.fighter.HeroFighter;
import cate.game.play.support.PlayBuildContext;
import cate.game.role.RoleSnapshot;
import com.fasterxml.jackson.annotation.JsonIgnore;
import cp.solution.pattern.ICopiable;
import cp.solution.util.collection.ListKit;
import cp.solution.util.collection.MapKit;
import easy.java.dev.note.NoteClass;
import easy.java.dev.note.NoteField;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@NoteClass("剧本一方")
public class PlaySide implements ICopiable<PlaySide> {

	@NoteField("玩家快照")
	public RoleSnapshot snapshot;

	@NoteField("阵型模板ID")
	public int positionTid;

	@NoteField("上阵的英雄们")
	public List<BattleHero> hs = new ArrayList<>();

	@NoteField("主圣器")
	public BattleHallow hallow;

	@NoteField("副圣器")
	public BattleHallow deputyHallow;

	@NoteField("灵宠")
	public Map<Integer,BattlePet> pets;

	public void addHero(BattleHero hero) {
		if (existPos(hero.pos)) {
			return;
		}
		hs.add(hero);
	}

	public void setHallow(BattleHallow hallow) {
		this.hallow = hallow;
	}

	public void setDeputyHallow(BattleHallow deputyHallow) {this.deputyHallow = deputyHallow;}

	public void setPets(int pos, BattlePet pet) {
		if (pets == null) {
			pets = new HashMap<>();
		}
		pets.put(pos, pet);
	}

	private boolean existPos(byte pos) {
		for (BattleHero battleHero : hs) {
			if (battleHero.pos == pos) {
				return true;
			}
		}
		return false;
	}

	public List<HeroFighter> buildHeroFighters(PlayBuildContext ctx){
		List<HeroFighter> list = new ArrayList<>();
		for (BattleHero h : hs) {
			HeroFighter fighter = h.buildFighter(ctx);
			list.add(fighter);
		}
		return list;
	}

	public HallowFighter buildHallowFighter(boolean deputy) {
		if (deputy) {
			if (deputyHallow != null) {
				return deputyHallow.buildFighter();
			}
		} else {
			if (hallow != null) {
				return hallow.buildFighter();
			}
		}
		return null;
	}



	@JsonIgnore
	public long getTotalPower() {
		long power = 0L;
		for (BattleHero h : hs) {
			power += h.power;
		}
		return power;
	}

	/**
	 * 更新战力（根据playside里的上阵英雄篡改roleBase里的战力）
	 */
	public void updatePower(){
		this.snapshot.base.power = getTotalPower();
	}

	@Override
	public PlaySide copy() {
		PlaySide cp = new PlaySide();
		cp.snapshot = this.snapshot != null ? this.snapshot.copy() : null;
		cp.positionTid = this.positionTid;
		cp.hs = ListKit.cloneList(this.hs, BattleHero::copy);
		cp.hallow = this.hallow != null ? this.hallow.copy() : null;
		cp.deputyHallow = this.deputyHallow != null ? this.deputyHallow.copy() : null;
		cp.pets = MapKit.cloneDeep(pets);
		return cp;
	}
}
